package com.bookseek.xreader.views;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bookseek.xreader.R;
import com.bookseek.xreader.consts.XreaderConts;
import com.bookseek.xreader.params.BookSearchParams;
import com.bookseek.xreader.service.NbSqlQueryManager;
import com.bookseek.xreader.service.dk.BdocService;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.DxmItemClickListener;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.utils.OkHttpUtils;
import com.bookseek.xreader.views.adapter.BdocLoadMoreAdapter;
import com.bookseek.xreader.views.adapter.LastItemNoDividerDecoration;
import com.bookseek.xreader.views.helper.SearchViewHelper;
import com.bookseek.xreader.views.reader.BookReaderActivity;
import com.bookseek.xreader.vo.BookListItemVo;
import com.bookseek.xreader.vo.TraceTextVo;
import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;
import java.util.List;

public class SlideSearchActivity extends AppCompatActivity implements View.OnClickListener, DxmItemClickListener {

    private DrawerLayout drawerLayout;

    private SearchViewHelper searchHelper;

    private RecyclerView bookListRv;


    private RadioGroup matchGroupRg;

    private TextInputLayout bauthorTextField;
    private TextInputLayout btitleTextField;
    private TextInputLayout bcontTextField;
    private TextInputLayout bchaoTextField;

    private String keyword = ""; //关键词查找


    private Integer SEAARCH_MODE = 1;// 1=关键词搜索模式 2=精确搜索模式

    private Integer PAGE_SIZE = 20; //分页大小

    private Integer CUR_PAGE = 1;//当前叶

    private boolean isLoading = false;//是否正则加载

    private boolean hasMoreData = true;//是否有更多数据

    private BdocLoadMoreAdapter adapter;

    private List<BookListItemVo> datas = new ArrayList<>();

    private Integer MATCH_MODE = 1;// 1=模糊匹配 2=精确皮欸
    //高亮文本颜色

    private String btype;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initParams();
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_slide_search);
        drawerLayout = findViewById(R.id.searchDrawerLayout);
        setListeners();
        //初始化搜索组件
        initSearchComponent();
        initBookListRv();
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.slideSearchTop), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        DLog.info("onCreate===========>Build.VERSION.SDK_INT=",Build.VERSION.SDK_INT,"Build.VERSION_CODES.TIRAMISU=",Build.VERSION_CODES.TIRAMISU);

        // 对于Android 13及以上版本使用新机制
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
           getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
               @Override
               public void handleOnBackPressed() {
                    if(handleBackCloseActivity()){
                        DLog.info("查询结果页面销毁------------》");
                        finish();
                    }
               }
           });
        }
        //加载数据
        loadData();
    }

    private void initParams(){
        Intent intent = getIntent();
        btype = intent.getStringExtra("btype");
    }
    private void searchData(BookSearchParams params){
        isLoading = true;
        adapter.setLoadState(BdocLoadMoreAdapter.LOADING);
        params.btype = JkhlUtils.notBlank(btype) ? btype : XreaderConts.BTYPE_SHICI;
        NbSqlQueryManager.getInstance().queryBdocByBtype(params, new OkHttpUtils.SqlCallback<List<BookListItemVo>>() {
            @Override
            public void onSuccess(List<BookListItemVo> result) {
                    int size = result.size();
                    datas.addAll(result);
                    adapter.notifyDataSetChanged();
                    isLoading = false;
                    hasMoreData = size >= PAGE_SIZE;
                    DLog.info("回调OK---> 记录数 ",size," hasMoreData=",hasMoreData);
                    if(hasMoreData){
                        adapter.setLoadState(BdocLoadMoreAdapter.LOADING_COMPLETE);
                    }else{
                        adapter.setLoadState(BdocLoadMoreAdapter.LOADING_END);
                    }
            }

            @Override
            public void onError(Exception e) {
                isLoading = false;
                adapter.setLoadState(BdocLoadMoreAdapter.LOADING_ERROR); // 显示加载错误
            }
        });

    }

    private void searchKeyword(){
        BookSearchParams params = new BookSearchParams();
        params.keyword = keyword;
        params.setPage(CUR_PAGE);
        params.setPageSize(PAGE_SIZE);
        params.searchMode = SEAARCH_MODE;

        searchData(params);
    }

    private void searchField(){
        BookSearchParams params = new BookSearchParams();
        params.setPage(CUR_PAGE);
        params.setPageSize(PAGE_SIZE);
        params.searchMode = SEAARCH_MODE;
        params.matchMode = MATCH_MODE;
        // 通过 TextInputLayout 获取内部的 EditText
        EditText bauthorEditText = bauthorTextField.getEditText();
        EditText bchaoEditText = bchaoTextField.getEditText();
        EditText bcontEditText = bcontTextField.getEditText();
        EditText btitleEditText = btitleTextField.getEditText();
        if(bauthorEditText != null){
            params.bauthor = bauthorEditText.getText().toString().trim();
        }
        if(bcontEditText != null){
            params.bcont = bcontEditText.getText().toString().trim();
        }
        if(btitleEditText != null){
            params.btitle = btitleEditText.getText().toString().trim();
        }
        if(bchaoEditText != null){
            params.bchao = bchaoEditText.getText().toString().trim();
        }
        searchData(params);
    }

    //加载数据
    private void loadData(){
        BookSearchParams searchParams = new BookSearchParams();
        searchParams.setPageSize(PAGE_SIZE);
        searchParams.setPage(CUR_PAGE);
        if(SEAARCH_MODE == 1){
            searchKeyword();
        }else{
            searchField();
        }
    }
    private void initBookListRv(){
        bookListRv = findViewById(R.id.bookListRv);
        adapter = new BdocLoadMoreAdapter(datas,this,btype);
        // 参数：上下文、分割线颜色、分割线高度资源
        bookListRv.addItemDecoration(new LastItemNoDividerDecoration(
                this,
                XreaderConts.DIVIDER_COLOR,  // 分割线颜色
                R.dimen.divider_height                           // 分割线高度（在dimens.xml中定义）
        ));
        //new LinearLayoutManager(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        bookListRv.setLayoutManager(layoutManager);
        bookListRv.setAdapter(adapter);
        bookListRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                // 只处理向上滚动
                if (dy <= 0) return;

                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                if (!isLoading && hasMoreData && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0) {
                    isLoading = true;
                    CUR_PAGE++;
                    DLog.info("查询更多---》 ",CUR_PAGE);
                    bookListRv.post(()->{
                        loadData();
                    });
                }
            }
        });
    }

    private void resetData(){
        datas.clear();
        CUR_PAGE = 1;
        hasMoreData = true;
        isLoading = false;
        adapter.notifyDataSetChanged();
    }
    private void initDrawSearchComponent(){

    }
    private void initSearchComponent(){
        ImageView clearButton = findViewById(R.id.iv_clear);
        // 初始化搜索栏组件
        EditText searchEditText = findViewById(R.id.et_search);
        bcontTextField = findViewById(R.id.bcontTextField);
        btitleTextField = findViewById(R.id.btitleTextField);
        bauthorTextField = findViewById(R.id.bauthorTextField);
        bchaoTextField = findViewById(R.id.bchaoTextField);

        // 创建搜索助手
        searchHelper = new SearchViewHelper(this, searchEditText, clearButton);

        // 设置搜索监听
        searchHelper.setOnSearchListener(new SearchViewHelper.OnSearchListener() {
            @Override
            public void onSearch(String query) {
                // 处理搜索逻辑
                //Toast.makeText(SlideSearchActivity.this, "搜索: " + query, Toast.LENGTH_SHORT).show();
                //需要清空原始数据
                SEAARCH_MODE = 1;
                DLog.info("执行搜索--->",query);
                resetData();
                searchKeyword();
            }

            @Override
            public void onTextChanged(String text) {
                // 处理文本变化（如实时搜索建议）
                // Log.d("Search", "文本变化: " + text);
                DLog.info("Search:","文本变化: " + text);
                keyword = text;
            }
        });

        matchGroupRg = findViewById(R.id.matchGroupRg);

        matchGroupRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                MATCH_MODE = checkedId == R.id.eqMatchRd ? 2 : 1;
                RadioButton radioButton = findViewById(checkedId);
                String text = radioButton.getText().toString();
                DLog.info("matchMode(1=模糊，2=精确)=",MATCH_MODE,text);
            }
        });

        // 应用筛选条件
        Button btnApplyFilter = findViewById(R.id.btnApplyFilter);
        btnApplyFilter.setOnClickListener(v -> {
            drawerLayout.closeDrawers();
            SEAARCH_MODE = 2;
            searchHelper.setSearchText("");
            resetData();
            loadData();
        });
    }
    private void setListeners() {
        // 打开侧边栏（筛选按钮点击）
        ImageView ivFilter = findViewById(R.id.ivFilter);
        ivFilter.setOnClickListener(v -> drawerLayout.openDrawer(findViewById(R.id.filterDrawer)));
        // 监听侧边栏状态变化
        drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // 侧边栏打开时的操作，如更新筛选状态
            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    // 按返回键时优先关闭侧边栏

    // 保留旧方法用于兼容低版本
    @Override
    public void onBackPressed() {
        DLog.info("onBackPressed===========>Build.VERSION.SDK_INT=",Build.VERSION.SDK_INT,"Build.VERSION_CODES.TIRAMISU=",Build.VERSION_CODES.TIRAMISU);
        // 对于Android 13以下版本使用旧机制
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            if(handleBackCloseActivity()){
                DLog.info("onBackPressed 查询结果页面销毁------------》");
                super.onBackPressed();
            }
        } else {
            super.onBackPressed(); // 对于高版本，交给dispatcher处理
        }
    }

    private boolean handleBackCloseActivity() {
        if (drawerLayout.isDrawerOpen(findViewById(R.id.filterDrawer))) {
            drawerLayout.closeDrawers();
            return false;
        } else {
            super.onBackPressed();
            return true;
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        BookListItemVo itemVo = adapter.getItem(position);
        DLog.info("点击了===POS==>",position,OkHttpUtils.gson.toJson(itemVo));
        if(XreaderConts.BTYPE_DIANJI.equalsIgnoreCase(itemVo.btype)){
            //跳转到典籍阅读界面
            Long bookid = itemVo.cid;
            Intent intent = new Intent(getApplicationContext(), BookReaderActivity.class);
            intent.putExtra("bookid",bookid);
            startActivity(intent);
        }
    }

    @Override
    public void onItemLongClick(View view, int position) {

    }
}